<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        .luck-draw{
            width: 80%;
            margin: 0 auto;
        }
        h2{
            line-height: 60px;
        }
        #btn{
            margin-top: 16px;
            display: block;
            height: 32px;
            border-radius: 5px;
            background: #28f;
            border: none;
            color: #fff;
            padding-left: 8px;
            padding-right: 8px;
        }
    </style>
</head>
<body>
    <div class="luck-draw">
        <h2>Promise实践AJAX请求</h2>
        <hr/>
        <button id="btn">请求数据</button>
    </div>
    <script>
        const btn = document.querySelector("#btn")
        btn.addEventListener("click", function(){
           const P = new Promise( (resolve, reject) => {
                //1.创建AJAX对象
                const xhr = new XMLHttpRequest();
                //2.初始化
                xhr.open('GET', 'https://api.apiopen.top/getJoke');
                //3.发送请求
                xhr.send()
                //4.处理响应结果
                xhr.onreadystatechange = function(){
                    if (xhr.readyState === 4) {
                        //判断状态码
                        if (xhr.status >= 200 && xhr.status < 300) {
                            //控制台打印响应体
                            resolve(xhr.response);
                        } else {
                            //控制台打印状态码
                            reject(xhr.status);
                        }
                    }
                } 
           });
           P.then( value => {
               console.log(value)
           }, reason => {
               console.warn(reason)
           })
            
       })
    </script>
</body>
</html>